package com.sikadwa.syc

import android.content.Context
import com.google.gson.Gson
import com.sikadwa.syc.data.SikadwaSysDataT1
import com.sikadwa.syc.data.SikadwaSysDataT2
import com.sikadwa.syc.data.SikadwaSysDataT3
import com.sikadwa.syc.data.SikadwaSysDataT4
import com.sikadwa.syc.data.SikadwaSysDataT5
import com.sikadwa.syc.data.SikadwaSysDataT7
import com.sikadwa.syc.util.SikadwaSysDataAesUtil

class SikadwaSysDataMode(val context: Context, val product: String, val token: String) {

    private fun formatSysDataType1(path: String, fetchData: () -> String?): String? {
        if (!formatJson(path)) return null
        val content = fetchData()?:""

        // TODO: 加密操作
        val encrypted: String = SikadwaSysDataAesUtil.encryptDefault(content)
        return encrypted
    }

    private fun formatSysDataType2(path: String, key: String, fetchData: () -> String?): String? {
        if (!formatJson(path)) return null
        val data = fetchData() ?: return null
        val params = baseJson(path).apply { put(key, data) }
        val content = Gson().toJson(params).trim()

        // TODO: 加密操作
        val encrypted: String = SikadwaSysDataAesUtil.encryptDefault(content)
        return encrypted
    }

    private fun formatJson(path: String) = listOf(product, token, path).all { it.isNotBlank() }

    private fun baseJson(path: String) = hashMapOf<String, Any>(
        "path" to path.replace("/", ""),
        "token" to token,
        "product" to product
    )

    fun onSiakdwaSubSysDataT1(path: String) = formatSysDataType1(path) {
        SikadwaSysDataT1(context, path).getSubmitDataT1()
    }

    fun onSiakdwaSubSysDataT7(path: String) = formatSysDataType1(path) {
        SikadwaSysDataT7(context, product, token, path).getSubmitDataT7()
    }

    fun onSiakdwaSubSysDataT3(path: String) = formatSysDataType2(path, "deviceHardwareGzip") {
        SikadwaSysDataT3(context).getSubmitDataT3()
    }

    fun onSiakdwaSubSysDataT2(path: String, onResult: (String?) -> Unit) {
        SikadwaSysDataT2(context = context, onResult = { bd ->
            val result = formatSysDataType2(path, "deviceBatteryGzip") { bd }
            onResult.invoke(result)
        }).start()
    }

    fun onSiakdwaSubSysDataT5(path: String) = formatSysDataType2(path, "deviceWifiGzip") {
        SikadwaSysDataT5(context).getSubmitDataT5()
    }

    fun onSiakdwaSubSysDataT4(path: String) = formatSysDataType2(path, "deviceStorageGzip") {
        SikadwaSysDataT4(context).getSubmitDataT4()
    }
}